// 全局变量
let tasks = [];
let currentFilter = 'all';
let editingTaskId = null;

// DOM 元素
const taskInput = document.getElementById('taskInput');
const addBtn = document.getElementById('addBtn');
const taskList = document.getElementById('taskList');
const filterBtns = document.querySelectorAll('.filter-btn');
const clearCompletedBtn = document.getElementById('clearCompleted');
const emptyState = document.getElementById('emptyState');
const editModal = document.getElementById('editModal');
const editTaskInput = document.getElementById('editTaskInput');
const saveEditBtn = document.getElementById('saveEdit');
const cancelEditBtn = document.getElementById('cancelEdit');
const closeModalBtn = document.getElementById('closeModal');

// 计数器元素
const allCount = document.getElementById('allCount');
const activeCount = document.getElementById('activeCount');
const completedCount = document.getElementById('completedCount');
const todayTasks = document.getElementById('todayTasks');
const completionRate = document.getElementById('completionRate');

// 初始化应用
document.addEventListener('DOMContentLoaded', function() {
    loadTasks();
    bindEvents();
    updateDisplay();
});

// 绑定事件
function bindEvents() {
    // 添加任务
    addBtn.addEventListener('click', addTask);
    taskInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            addTask();
        }
    });

    // 过滤器
    filterBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            setFilter(this.dataset.filter);
        });
    });

    // 清除已完成任务
    clearCompletedBtn.addEventListener('click', clearCompleted);

    // 编辑模态框
    saveEditBtn.addEventListener('click', saveEdit);
    cancelEditBtn.addEventListener('click', closeEditModal);
    closeModalBtn.addEventListener('click', closeEditModal);

    // 点击模态框外部关闭
    editModal.addEventListener('click', function(e) {
        if (e.target === editModal) {
            closeEditModal();
        }
    });

    // 编辑输入框回车保存
    editTaskInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            saveEdit();
        }
    });
}

// 任务类
class Task {
    constructor(text) {
        this.id = Date.now() + Math.random();
        this.text = text.trim();
        this.completed = false;
        this.createdAt = new Date();
        this.completedAt = null;
    }

    toggle() {
        this.completed = !this.completed;
        this.completedAt = this.completed ? new Date() : null;
    }

    edit(newText) {
        this.text = newText.trim();
    }

    getFormattedDate() {
        return this.createdAt.toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: 'short',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        });
    }

    isToday() {
        const today = new Date();
        const taskDate = this.createdAt;
        return today.toDateString() === taskDate.toDateString();
    }
}

// 添加任务
function addTask() {
    const text = taskInput.value.trim();
    
    if (!text) {
        showNotification('请输入任务内容', 'warning');
        taskInput.focus();
        return;
    }

    if (text.length > 100) {
        showNotification('任务内容不能超过100个字符', 'error');
        return;
    }

    const task = new Task(text);
    tasks.unshift(task); // 新任务添加到顶部
    
    taskInput.value = '';
    saveTasks();
    updateDisplay();
    showNotification('任务添加成功', 'success');
}

// 删除任务
function deleteTask(taskId) {
    if (confirm('确定要删除这个任务吗？')) {
        tasks = tasks.filter(task => task.id !== taskId);
        saveTasks();
        updateDisplay();
        showNotification('任务已删除', 'success');
    }
}

// 切换任务状态
function toggleTask(taskId) {
    const task = tasks.find(t => t.id === taskId);
    if (task) {
        task.toggle();
        saveTasks();
        updateDisplay();
        
        const message = task.completed ? '任务已完成' : '任务已标记为未完成';
        showNotification(message, 'success');
    }
}

// 编辑任务
function editTask(taskId) {
    const task = tasks.find(t => t.id === taskId);
    if (task) {
        editingTaskId = taskId;
        editTaskInput.value = task.text;
        showEditModal();
    }
}

// 显示编辑模态框
function showEditModal() {
    editModal.classList.add('show');
    editTaskInput.focus();
    editTaskInput.select();
}

// 关闭编辑模态框
function closeEditModal() {
    editModal.classList.remove('show');
    editingTaskId = null;
    editTaskInput.value = '';
}

// 保存编辑
function saveEdit() {
    const newText = editTaskInput.value.trim();
    
    if (!newText) {
        showNotification('请输入任务内容', 'warning');
        editTaskInput.focus();
        return;
    }

    if (newText.length > 100) {
        showNotification('任务内容不能超过100个字符', 'error');
        return;
    }

    const task = tasks.find(t => t.id === editingTaskId);
    if (task) {
        task.edit(newText);
        saveTasks();
        updateDisplay();
        closeEditModal();
        showNotification('任务已更新', 'success');
    }
}

// 设置过滤器
function setFilter(filter) {
    currentFilter = filter;
    
    // 更新按钮状态
    filterBtns.forEach(btn => {
        btn.classList.toggle('active', btn.dataset.filter === filter);
    });
    
    updateDisplay();
}

// 清除已完成任务
function clearCompleted() {
    const completedTasks = tasks.filter(task => task.completed);
    
    if (completedTasks.length === 0) {
        showNotification('没有已完成的任务', 'info');
        return;
    }

    if (confirm(`确定要删除 ${completedTasks.length} 个已完成的任务吗？`)) {
        tasks = tasks.filter(task => !task.completed);
        saveTasks();
        updateDisplay();
        showNotification(`已删除 ${completedTasks.length} 个已完成任务`, 'success');
    }
}

// 获取过滤后的任务
function getFilteredTasks() {
    switch (currentFilter) {
        case 'active':
            return tasks.filter(task => !task.completed);
        case 'completed':
            return tasks.filter(task => task.completed);
        default:
            return tasks;
    }
}

// 更新显示
function updateDisplay() {
    updateTaskList();
    updateCounts();
    updateStats();
}

// 更新任务列表
function updateTaskList() {
    const filteredTasks = getFilteredTasks();
    
    taskList.innerHTML = '';
    
    if (filteredTasks.length === 0) {
        emptyState.style.display = 'block';
        return;
    }
    
    emptyState.style.display = 'none';
    
    filteredTasks.forEach(task => {
        const taskElement = createTaskElement(task);
        taskList.appendChild(taskElement);
    });
}

// 创建任务元素
function createTaskElement(task) {
    const li = document.createElement('li');
    li.className = `task-item ${task.completed ? 'completed' : ''}`;
    li.dataset.taskId = task.id;
    
    li.innerHTML = `
        <div class="task-checkbox ${task.completed ? 'checked' : ''}" 
             onclick="toggleTask(${task.id})"></div>
        <div class="task-content">
            <div class="task-text">${escapeHtml(task.text)}</div>
            <div class="task-meta">
                <span><i class="fas fa-calendar"></i> ${task.getFormattedDate()}</span>
                ${task.completed ? `<span><i class="fas fa-check-circle"></i> 已完成</span>` : ''}
            </div>
        </div>
        <div class="task-actions">
            <button class="action-btn edit-btn" onclick="editTask(${task.id})" title="编辑">
                <i class="fas fa-edit"></i>
            </button>
            <button class="action-btn delete-btn" onclick="deleteTask(${task.id})" title="删除">
                <i class="fas fa-trash"></i>
            </button>
        </div>
    `;
    
    return li;
}

// 更新计数
function updateCounts() {
    const all = tasks.length;
    const active = tasks.filter(task => !task.completed).length;
    const completed = tasks.filter(task => task.completed).length;
    
    allCount.textContent = all;
    activeCount.textContent = active;
    completedCount.textContent = completed;
}

// 更新统计信息
function updateStats() {
    const today = tasks.filter(task => task.isToday()).length;
    const total = tasks.length;
    const completed = tasks.filter(task => task.completed).length;
    const rate = total > 0 ? Math.round((completed / total) * 100) : 0;
    
    todayTasks.textContent = today;
    completionRate.textContent = `${rate}%`;
}

// 保存任务到本地存储
function saveTasks() {
    try {
        localStorage.setItem('todoTasks', JSON.stringify(tasks.map(task => ({
            id: task.id,
            text: task.text,
            completed: task.completed,
            createdAt: task.createdAt.toISOString(),
            completedAt: task.completedAt ? task.completedAt.toISOString() : null
        }))));
    } catch (error) {
        console.error('保存任务失败:', error);
        showNotification('保存失败，请检查浏览器存储空间', 'error');
    }
}

// 从本地存储加载任务
function loadTasks() {
    try {
        const savedTasks = localStorage.getItem('todoTasks');
        if (savedTasks) {
            const parsedTasks = JSON.parse(savedTasks);
            tasks = parsedTasks.map(taskData => {
                const task = new Task(taskData.text);
                task.id = taskData.id;
                task.completed = taskData.completed;
                task.createdAt = new Date(taskData.createdAt);
                task.completedAt = taskData.completedAt ? new Date(taskData.completedAt) : null;
                return task;
            });
        }
    } catch (error) {
        console.error('加载任务失败:', error);
        tasks = [];
        showNotification('加载任务失败，将从空列表开始', 'warning');
    }
}

// HTML 转义
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// 显示通知
function showNotification(message, type = 'info') {
    // 移除现有通知
    const existingNotification = document.querySelector('.notification');
    if (existingNotification) {
        existingNotification.remove();
    }
    
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.innerHTML = `
        <div class="notification-content">
            <i class="fas fa-${getNotificationIcon(type)}"></i>
            <span>${message}</span>
        </div>
    `;
    
    // 添加样式
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: ${getNotificationColor(type)};
        color: white;
        padding: 15px 20px;
        border-radius: 10px;
        box-shadow: 0 10px 20px rgba(0,0,0,0.2);
        z-index: 10000;
        animation: slideInRight 0.3s ease;
        max-width: 300px;
        word-wrap: break-word;
    `;
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 3秒后自动移除
    setTimeout(() => {
        if (notification.parentNode) {
            notification.style.animation = 'slideOutRight 0.3s ease';
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.remove();
                }
            }, 300);
        }
    }, 3000);
}

// 获取通知图标
function getNotificationIcon(type) {
    switch (type) {
        case 'success': return 'check-circle';
        case 'error': return 'exclamation-circle';
        case 'warning': return 'exclamation-triangle';
        default: return 'info-circle';
    }
}

// 获取通知颜色
function getNotificationColor(type) {
    switch (type) {
        case 'success': return '#28a745';
        case 'error': return '#dc3545';
        case 'warning': return '#ffc107';
        default: return '#17a2b8';
    }
}

// 添加通知动画样式
const notificationStyles = document.createElement('style');
notificationStyles.textContent = `
    @keyframes slideInRight {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
    
    @keyframes slideOutRight {
        from {
            transform: translateX(0);
            opacity: 1;
        }
        to {
            transform: translateX(100%);
            opacity: 0;
        }
    }
    
    .notification-content {
        display: flex;
        align-items: center;
        gap: 10px;
    }
`;
document.head.appendChild(notificationStyles);

// 键盘快捷键
document.addEventListener('keydown', function(e) {
    // Ctrl/Cmd + Enter 快速添加任务
    if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
        if (document.activeElement === taskInput) {
            addTask();
        }
    }
    
    // ESC 关闭模态框
    if (e.key === 'Escape') {
        if (editModal.classList.contains('show')) {
            closeEditModal();
        }
    }
});

// 导出数据功能
function exportTasks() {
    const dataStr = JSON.stringify(tasks, null, 2);
    const dataBlob = new Blob([dataStr], {type: 'application/json'});
    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `todo-tasks-${new Date().toISOString().split('T')[0]}.json`;
    link.click();
    URL.revokeObjectURL(url);
    showNotification('任务数据已导出', 'success');
}

// 导入数据功能
function importTasks(event) {
    const file = event.target.files[0];
    if (!file) return;
    
    const reader = new FileReader();
    reader.onload = function(e) {
        try {
            const importedTasks = JSON.parse(e.target.result);
            if (Array.isArray(importedTasks)) {
                tasks = importedTasks.map(taskData => {
                    const task = new Task(taskData.text);
                    task.id = taskData.id || Date.now() + Math.random();
                    task.completed = taskData.completed || false;
                    task.createdAt = new Date(taskData.createdAt || Date.now());
                    task.completedAt = taskData.completedAt ? new Date(taskData.completedAt) : null;
                    return task;
                });
                saveTasks();
                updateDisplay();
                showNotification('任务数据导入成功', 'success');
            } else {
                throw new Error('无效的数据格式');
            }
        } catch (error) {
            console.error('导入失败:', error);
            showNotification('导入失败，请检查文件格式', 'error');
        }
    };
    reader.readAsText(file);
}

// 页面可见性变化时保存数据
document.addEventListener('visibilitychange', function() {
    if (document.hidden) {
        saveTasks();
    }
});

// 页面卸载前保存数据
window.addEventListener('beforeunload', function() {
    saveTasks();
});